import os
import json
from PIL import Image

def load_label_map(label_map_file):
    with open(label_map_file, 'r', encoding='utf-8') as f:
        label_map = json.load(f)
    reversed_label_map = {v: int(k) for k, v in label_map.items()}
    return reversed_label_map

def convert_json_format(json_file, image_folder, label_map):
    with open(json_file, 'r', encoding='utf-8') as f:
        data = json.load(f)

    filename = data['imagePath']
    image_path = os.path.join(image_folder, filename)
    with Image.open(image_path) as img:
        width, height = img.size

    instances = []
    for shape in data['shapes']:
        category = shape['label']
        points = shape['points']
        xmin = float(points[0][0])
        ymin = float(points[0][1])
        xmax = float(points[1][0])
        ymax = float(points[1][1])
        if category == 'person':
            category = 'overhead view worker'
        label = label_map.get(category, -1)  # 获取类别对应的标签值，若不存在则设为-1
        if label == -1:
            print(f"Warning: Category '{category}' not found in label map.")
        instance = {
            "bbox": [xmin, ymin, xmax, ymax],
            "label": 0,  # 这里假设所有类别的标签都是0，你可以根据需要修改
            "category": category
        }
        instances.append(instance)

    json_data = {
        "filename": filename,
        "height": height,
        "width": width,
        "detection": {
            "instances": instances
        }
    }

    return json_data

def convert_folder_to_jsonl(json_folder, output_file, image_folder, label_map_file):
    label_map = load_label_map(label_map_file)
    with open(output_file, 'w', encoding='utf-8') as f:
        for filename in os.listdir(json_folder):
            if filename.endswith('.json'):
                json_file = os.path.join(json_folder, filename)
                json_data = convert_json_format(json_file, image_folder, label_map)
                f.write(json.dumps(json_data, ensure_ascii=False) + '\n')

# 示例用法
json_folder = 'Meishan/Meishan_240830/annotations'  # 替换为你的JSON文件夹路径
image_folder = 'Meishan/Meishan_240830/images'  # 替换为你的图片文件夹路径
output_file = 'Meishan/annotation/Meishan_240830.jsonl'
label_map_file = 'Meishan/annotation/label_map.json'  # 替换为你的label_map.json文件路径
convert_folder_to_jsonl(json_folder, output_file, image_folder, label_map_file)